<template>
    <div id="pageHeight" class="dial-container page page-group">
        <div class="content bg-red1" v-show="gameShow">
            <img src="/images/1.png" id="shan-img" style="display:none;" />
            <img src="/images/2.png" id="sorry-img" style="display:none;" />
            <div class="rule-button"><van-button round size="small" type="primary" @click="showRule">查看规则</van-button></div>
            <div class="banner">
                <div class="turnplate" style="background-image:url(/images/turnplate-bg.png);background-size:100% 100%;">
                    <canvas class="item" id="wheelcanvas" width="422px" height="422px"></canvas>
                    <button class="pointer" src="/images/turnplate-pointer.png" v-on:click="pointer" id="disabledfn">
                    </button>
                </div>
            </div>
            <div class="dial_change">您今日还有 <span style="color: rgb(253, 232, 23);" id="change"> {{lotteryNumber}} </span> 次抽奖机会
            </div>
            <div class="wheel_lottery_module" v-show="detailShow">
                <div class="winning_list_wrap ">
                    <img src="/images/zj.jpg" alt="" class=" fadein">
                    <div class="winning_list jdui_slide" id="winninglist">
                        <vue-seamless-scroll :data="listData" :class-option="classOption">
                            <ul class="jdui_slide_list ">
                                <li style="height: 28px;" v-for="item in listData">
                                    <span>{{item.user}}</span><span>抽到</span><span>{{item.prize}}</span>
                                </li>
                            </ul>
                        </vue-seamless-scroll>
                    </div>
                </div>
            </div>
            <div class="award-button"><van-button size="small" type="warning" @click="goToOrder">我的中奖记录</van-button>
                <padding-bottom :height="70"/>
            </div>
            <!--<occupy-block :height="70"/>-->
        </div>
        <div class="content offShow" v-show="gameOffShow">
            {{clues}}
        </div>
        <van-popup v-model="ruleShow" >
            <div class="ruleTitle">
                <div class="ruleText">活动规则：</div><img @click="showRule" src="/images/ticket_close.png" class="ticket_close">
            </div>
            <div class="ruleBorder" v-html="rule"></div>
        </van-popup>
    </div>
</template>

<script type="text/ecmascript-6">
    import Vue from 'vue'
    import {Toast,Dialog,Loading} from 'vant';
    import Cookies from 'js-cookie';
    import scroll from 'vue-seamless-scroll'
    import {jq} from '@/assets/js/jquery-2.1.1.min';
    import {myfun} from '@/assets/js/awardRotate';
    Vue.use(Loading);
    Vue.use(scroll)
    export default {
        name: 'awardRotate',
        data () {
            return {
                msg: '',
                turnplate: {
                    restaraunts: [],
                    colors: [],
                    outsideRadius: 192,
                    textRadius: 155,
                    insideRadius: 68,
                    startAngle: 0,
                    bRotate: false
                },
                token:'',
                rule:'',
                ruleShow:false,
                lotteryNumber:'',
                gameId:0,
                gameShow:true,
                gameOffShow:false,
                detailShow:false,
                clues:'抽奖活动未开启，敬请期待！',
                listData: [{
                }]
            }
        },
        created () {
            document.title = '大转盘抽奖'
            let that = this
            this.token = Cookies.get("token")
            this.$api.dial.gameSettingList({openid: this.token}).then(res=>{
                if(res.code==0){
                    var data = JSON.parse(res.data)
                    console.log(data)
                    var success = data.success
                    if(success){
                        if(data.gameType == "1"){
                            Dialog.alert({
                                message: '温馨提示：本次抽奖活动仅限现场持票观众参与，中奖用户需凭票领取奖品。'
                            }).then(() => {
                                // on close
                            });
                        }
                        this.rule = data.rule;
                        this.lotteryNumber = data.lotteryNumber
                        this.gameId = data.gameId
                        if(data.detailShow == true){
                            this.detailShow = true
                        }
                        this.listData = data.listData
                        this.$nextTick(() => {
                            this.turnplate.restaraunts = data.prizeArry
                            this.turnplate.colors = ['#FFF4D6', '#FFFFFF', '#FFF4D6', '#FFFFFF', '#FFF4D6', '#FFFFFF', '#FFF4D6', '#FFFFFF', '#FFF4D6', '#FFFFFF', '#FFF4D6']
                            this.rotateTimeOut()
                            this.rotateFn()
                            $(document).ready(function () {
                                // 解决转盘图片不加载
                                that.drawRouletteWheel()
                            })
                        })
                    }else{
                        this.gameShow = !this.gameShow
                        this.gameOffShow = !this.gameOffShow
                        console.log(data)
                        console.log(data.clues)
                        if(data.clues != null && data.clues != ''){
                            this.clues = data.clues
                        }
                    }
                }
            }).catch(err=>{
                console.log(err)
            })
        },
        computed: {
            classOption () {
                return {
                    hoverStop: false,
                    openTouch: false
                }
            }
        },
        mounted() {
            var html = document.getElementById("winninglist").children[0].children[0]
            html.setAttribute("class", "width100");
        },
        methods: {
            rotateTimeOut: function () {
                $('#wheelcanvas').rotate({
                    angle: 0,
                    animateTo: 2160,
                    duration: 8000,
                    callback: function () {
                        Toast({message: '网络超时，请检查您的网络设置！', position: 'middle'})
                    }
                })
            },
            rotateFn: function (item, txt, authentication, prizeType) {
                var angles = item * (360 / this.turnplate.restaraunts.length) - (360 / (this.turnplate.restaraunts.length * 2))
                if (angles < 270) {
                    angles = 270 - angles
                } else {
                    angles = 360 - angles + 270
                }
                var bRotateT = this.turnplate.bRotate
                var _this = this
                this.$nextTick(() => {
                    $('#wheelcanvas').stopRotate()
                    $('#wheelcanvas').rotate({
                        angle: 0,
                        animateTo: angles + 1800,
                        duration: 8000,
                        callback:function (){
                            document.getElementById("disabledfn").disabled=false
                            if(prizeType == "3"){
                                Dialog.alert({
                                    title: '提示',
                                    className: 'dailfontsize',
                                    message: txt
                                }).then(() => {
                                });
                            }else{
                                var prize = "<span style='color:#e60012'>" + txt + "</span>";
                                if(prizeType == "0"){
                                    Dialog.confirm({
                                        title: '恭喜你',
                                        className: 'dailfontsize',
                                        message: '获得' + prize + '<br>请填写联系信息'
                                    }).then(() => {
                                        _this.goToView('/congratulationl',authentication)
                                    }).catch(() => {
                                        // on cancel
                                    });
                                }else if(prizeType == "1"){
                                    Dialog.alert({
                                        title: '恭喜你',
                                        className: 'dailfontsize',
                                        message: '获得:' + prize
                                    }).then(() => {
                                        // on close
                                    });
                                }else if (prizeType == "2"){
                                    Dialog.confirm({
                                        title: '恭喜你',
                                        className: 'dailfontsize',
                                        message: '获得' + prize + '<br>立刻支付'
                                    }).then(() => {
                                        _this.goToView('/congratulationl',authentication)
                                    }).catch(() => {
                                        // on cancel
                                    });
                                }
                            }
                        }
                    })
                })
                this.turnplate.bRotate = !bRotateT
            },
            pointer () {
                document.getElementById("disabledfn").disabled=true
                // if (this.turnplate.bRotate) return
                this.turnplate.bRotate = !this.turnplate.bRotate
                const toast = Toast.loading({
                    mask: true,
                    forbidClick: true,
                    message: '加载中...',
                    duration:0
                });
                this.$api.dial.gameSettingRaffle({openid:this.token,gameId:this.gameId}).then(res=>{
                    if(res.code==0){
                        toast.clear()
                        var data = JSON.parse(res.data)
                        var success = data.success;
                        var msg = data.msg;
                        var lotteryNumber = data.lotteryNumber;
                        var prizeType = data.prizeType;
                        console.log("prizeType:" + data.prizeType)
                        if(lotteryNumber != undefined){
                            this.lotteryNumber = lotteryNumber
                        }
                        if(success) {
                            var item = data.msg;
                            var authentication = data.authentication;
                            this.rotateFn(item + 1, this.turnplate.restaraunts[item],authentication,prizeType)
                        }else{
                            Dialog.alert({
                                title: '提示',
                                message: msg
                            }).then(() => {
                                document.getElementById("disabledfn").disabled=false
                            });
                            this.turnplate.bRotate = !this.turnplate.bRotate
                            return
                        }
                    }else {
                        toast.clear()
                        var data = res.data
                        Dialog.alert({
                            title: '提示',
                            message: data.msg
                        }).then(() => {
                            window.location.reload()
                        });
                    }
                }).catch(err=>{
                    Dialog.alert({
                        title: '提示',
                        message: '数据获取失败!'
                    }).then(() => {
                        document.getElementById("disabledfn").disabled=false
                    });
                    this.turnplate.bRotate = !this.turnplate.bRotate
                    return
                })
            },
            drawRouletteWheel () {
                var canvas = document.getElementById('wheelcanvas')
                if (canvas.getContext) {
                    // 根据奖品个数计算圆周角度
                    var arc = Math.PI / (this.turnplate.restaraunts.length / 2)
                    var ctx = canvas.getContext('2d')
                    // 在给定矩形内清空一个矩形
                    ctx.clearRect(0, 0, 422, 422)
                    // strokeStyle 属性设置或返回用于笔触的颜色、渐变或模式
                    ctx.strokeStyle = '#FFBE04'
                    // font 属性设置或返回画布上文本内容的当前字体属性
                    ctx.font = '16px Microsoft YaHei'
                    for (var i = 0; i < this.turnplate.restaraunts.length; i++) {
                        var angle = this.turnplate.startAngle + i * arc
                        ctx.fillStyle = this.turnplate.colors[i]
                        ctx.beginPath()
                        //  arc(x,y,r,起始角,结束角,绘制方向) 方法创建弧/曲线（用于创建圆或部分圆）
                        ctx.arc(211, 211, this.turnplate.outsideRadius, angle, angle + arc, false)
                        ctx.arc(211, 211, this.turnplate.insideRadius, angle + arc, angle, true)
                        ctx.stroke()
                        ctx.fill()
                        // 锁画布(为了保存之前的画布状态)
                        ctx.save()

                        // ----绘制奖品开始----
                        ctx.fillStyle = '#E5302F'
                        var text = this.turnplate.restaraunts[i]
                        var lineHeight = 17
                        // translate方法重新映射画布上的 (0,0) 位置
                        ctx.translate(211 + Math.cos(angle + arc / 2) * this.turnplate.textRadius, 211 + Math.sin(angle + arc / 2) * this.turnplate.textRadius)

                        // rotate方法旋转当前的绘图
                        ctx.rotate(angle + arc / 2 + Math.PI / 2)

                        /** 下面代码根据奖品类型、奖品名称长度渲染不同效果，如字体、颜色、图片效果。(具体根据实际情况改变) **/
                        if (text.indexOf('M') > 0) { // 流量包
                            var texts = text.split('M')
                            for (var j = 0; j < texts.length; j++) {
                                ctx.font = j === 0 ? 'bold 20px Microsoft YaHei' : '16px Microsoft YaHei'
                                if (j === 0) {
                                    ctx.fillText(texts[j] + 'M', -ctx.measureText(texts[j] + 'M').width / 2, j * lineHeight)
                                } else {
                                    ctx.fillText(texts[j], -ctx.measureText(texts[j]).width / 2, j * lineHeight)
                                }
                            }
                        } else if (text.indexOf('M') === -1 && text.length > 6) { // 奖品名称长度超过一定范围
                            text = text.substring(0, 6) + '||' + text.substring(6)
                            var textst = text.split('||')
                            for (var ji = 0; ji < textst.length; ji++) {
                                ctx.fillText(textst[ji], -ctx.measureText(textst[ji]).width / 2, ji * lineHeight)
                            }
                        } else {
                            // 在画布上绘制填色的文本。文本的默认颜色是黑色
                            // measureText()方法返回包含一个对象，该对象包含以像素计的指定字体宽度
                            ctx.fillText(text, -ctx.measureText(text).width / 2, 0)
                        }

                        // 添加对应图标
                        if (text.indexOf('Q币') > 0) {
                            var img = document.getElementById('shan-img')
                            ctx.drawImage(img, -15, 10)
                        } else if (text.indexOf('谢谢参与') >= 0) {
                            img = document.getElementById('sorry-img')
                            ctx.drawImage(img, -15, 10)
                        }
                        // 把当前画布返回（调整）到上一个save()状态之前
                        ctx.restore()
                        // 绘制奖品结束
                    }
                }
            },
            goToView(path,id){
                this.$router.push({path:path,query:{authentication:id}})
            },
            goToOrder(){
                this.$router.push('/order')
            },
            showRule(){
                this.ruleShow = !this.ruleShow
            }
        }
    }
</script>

<style lang="less">
    .dial-container{
        .page, .page-group {
            box-sizing: border-box;
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: #efeff4;
            overflow: hidden;
            right: 0;
            bottom: 0;
            z-index: 998;
        }
        .bg-red1 {
            /*background: #ff7575;*/
            background-color: #d20145;
        }
        .content {
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            overflow: auto;
            -webkit-overflow-scrolling: touch;
        }
        .dial_change {
            margin-top: 0.826667rem;
            text-align: center;
            font-size: 0.8rem;
            color: rgb(255, 255, 255);
        }
        .banner {
            width: 80%;
            display: block;
            margin-left: auto;
            margin-right: auto;
        }
        .banner .turnplate {
            display: block;
            width: 100%;
            position: relative;
        }
        .banner .turnplate canvas.item {
            width: 100%;
        }
        .banner .turnplate .pointer {
            position: absolute;
            width: 31.5%;
            height: 42.5%;
            left: 34.6%;
            top: 23%;
            border: 0;
            background: url(/images/turnplate-pointer.png) no-repeat;
            background-size: 100%;
        }
        .rule-button {
            text-align: right;
            margin-top: 0.826667rem;;
            margin-right: 0.826667rem;
        }
        .award-button {
            text-align: center;
            margin-top: 0.826667rem;
        }
        .offShow{
            text-align: center;
            margin-top: 80%;
            color: #bbbbbb;
            font-size: 18px;
        }

        .van-popup {
            position: fixed;
            top: 50%;
            left: 50%;
            max-height: 400px;
            overflow-y: auto;
            background-color: #fff;
            -webkit-transition: .3s ease-out;
            transition: .3s ease-out;
            -webkit-overflow-scrolling: touch;
            -webkit-transform: translate3d(-50%,-50%,0);
            transform: translate3d(-50%,-50%,0);
            padding: 0px 10px 10px 10px;
            width: 75%;
        }

        .jdui_slide {
            height: auto;
        }

        .wheel_lottery_module {
            position: relative;
            background-color: #d20145;
            margin: 0;
            padding: 0;
            overflow: hidden;
        }

        .wheel_lottery_module .winning_list_wrap {
            position: relative;
            padding-top: 51.6%;
            margin-top: -1px;
        }

        .wheel_lottery_module img {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
        }

        .wheel_lottery_module .winning_list_wrap .winning_list {
            position: absolute;
            bottom: 14%;
            left: 8.67%;
            width: 82.67%;
            height: 57.29%;
            overflow: hidden;
        }

        .wheel_lottery_module .winning_list_wrap .winning_list .jdui_slide_list  {
            width: 100%;
            height: 100%;
        }

        .jdui_slide .jdui_slide_list {
            -webkit-transition: all .3s ease;
            transition: all .3s ease;
        }

        .wheel_lottery_module .winning_list_wrap .winning_list .jdui_slide_list >li {
            display: block;
            height: 25%;
        }

        .wheel_lottery_module .winning_list_wrap .winning_list .jdui_slide_list >li>span:nth-child(3n+1) {
            width: 40%;
        }

        .wheel_lottery_module .winning_list_wrap .winning_list .jdui_slide_list >li>span {
            display: -webkit-box;
            font-size: 14px;
            color: #fff;
            float: left;
            height: 19px;
            line-height: 19px;
            overflow: hidden;
            text-overflow: ellipsis;
            -webkit-line-clamp: 1;
            -webkit-box-orient: vertical;
            word-break: break-all;
        }

        .wheel_lottery_module .winning_list_wrap .winning_list .jdui_slide_list >li>span:nth-child(3n) {
            width: 40%;
            text-align: right;
        }

        .wheel_lottery_module .winning_list_wrap .winning_list .jdui_slide_list >li>span:nth-child(3n+2) {
            width: 20%;
            font-size: 11px;
            text-align: center;
        }

        .ruleTitle{
            padding-top: 5px;
            text-align: right;
            height: 28px;
            border-bottom: 1px solid #7d7e80;
        }

        .ruleText{
            font-size: 16px;
            text-align: left;
        }

        .ruleTitle img {
            width: 40px;
            position: relative;
            top: -28px;
        }
    }
    .dailfontsize {
        font-size: 18px !important;
    }

    .dailfontsize .van-dialog__message {
        font-size: 18px !important;
    }

    .width100{
        width: 100% !important;
    }
</style>
